<template>
	<view class="container">
		<template v-if="taskInfo">
			<!-- 使用抽取的组件来显示核心任务信息 -->
			<task-info-display :taskInfo="taskInfo">
				<!-- 通过插槽放入此页面专属的操作按钮 -->
				<template v-slot:actions>
					<view class="right-section">
						<view class="follow-btn" :class="{ followed: isFollowing }" @click="toggleFollow">
							{{ isFollowing ? '已关注' : '关注' }}
						</view>
						<view class="action-menu-btn" @click="showActionMenu">
							<text class="dot">·</text>
							<text class="dot">·</text>
							<text class="dot">·</text>
						</view>
					</view>
				</template>
				<!-- 使用新插槽放置收藏按钮 -->
				<template v-slot:top-right>
					<view class="star-action" @click="toggleStar">
						<image class="star-icon" :src="starIconSrc"></image>
						<text class="star-count">{{ taskInfo.starCount || 0 }}</text>
					</view>
				</template>
				<!-- 新增：薪资水平展示 -->
				<view class="salary-info" style="margin: 16rpx 0 0 0; color: #ff6600; font-size: 30rpx; font-weight: bold;">
					薪资：{{ taskInfo.price }}{{ taskInfo.salaryUnit ? taskInfo.salaryUnit : '元' }}
				</view>
			</task-info-display>

			<!-- 报名用户列表（仅发布者可见） -->
			<view v-if="applicants && applicants.length > 0" class="applicants-section">
				<view class="section-title">报名列表 ({{ applicants.length }})</view>
				<view class="applicants-list">
					<view v-for="applicant in applicants" :key="applicant.userId" class="applicant-item">
						<image class="applicant-avatar" :src="getApplicantAvatar(applicant.avatar)" mode="aspectFill"></image>
						<text class="applicant-nickname">{{ applicant.nickName }}</text>
					</view>
				</view>
			</view>

			<!-- 占位，防止底部按钮遮挡 -->
			<view style="height: 120rpx;"></view>

			<!-- 底部操作栏 -->
			<view class="bottom-bar">
				<view class="left-actions">
					<view class="action-item" @click="callPhone(taskInfo.contactPhone)" v-if="taskInfo.contactPhone">
						<image class="action-icon-img" src="/static/img/电话.png"></image>
						<text class="text">打电话</text>
					</view>
					<view class="action-item" @click="chat">
						<image class="action-icon-img" src="/static/img/聊天.png"></image>
						<text class="text">聊一聊</text>
					</view>
				</view>
				<view class="apply-btn" :class="{ applied: hasApplied, disabled: applyCount >= (taskInfo.maxApplyCount || 1) && !hasApplied }" @tap="applyTask">
					{{ hasApplied ? '已报名' : '我要报名' }}（{{ applyCount }}/{{ taskInfo.maxApplyCount || 1 }}）
				</view>
			</view>

		</template>
		<template v-else>
			<view class="loading-tip">
				<text>加载中...</text>
			</view>
		</template>
	</view>
</template>

<script>
	import { getTaskInfo, deleteTask, applyTask as applyTaskApi, cancelApplyTask as cancelApplyTaskApi } from '@/api/task.js'
	import { toggleLike, toggleStar, toggleFollow } from '@/api/user'
	import config from '@/config/config.js'
	import { mapGetters } from 'vuex'
	import taskInfoDisplay from '@/components/task-info-display/task-info-display.vue'

	export default {
		components: {
			taskInfoDisplay
		},
		data() {
			return {
				taskId: null,
				taskInfo: null,
				isLiked: false,
				isStarred: false,
				isFollowing: false,
				hasApplied: false,
				applyCount: 0,
				followInProgress: false,
				applicants: []
			}
		},
		computed: {
			...mapGetters('user', ['userInfo', 'isLogin']),
			isPublisher() {
				return this.isLogin && this.taskInfo && this.userInfo && this.taskInfo.createBy == this.userInfo.userId;
			},
			likeIconSrc() {
				return this.isLiked ? '/static/img/已关注.png' : '/static/img/未关注.png';
			},
			starIconSrc() {
				return this.isStarred ? '/static/img/已收藏.png' : '/static/img/未收藏.png';
			}
		},
		onLoad(options) {
			if (options.taskId) {
				this.taskId = options.taskId
				this.getTaskDetail()
			}
		},
		methods: {
			// 获取任务详情
			async getTaskDetail() {
				try {
					uni.showLoading({
						title: '加载中...',
						mask: true
					});
					const res = await getTaskInfo(this.taskId)
					if (res.code === 200) {
						const data = res.data;
						const taskInfo = data.taskInfo || data;

						this.taskInfo = taskInfo;
						this.hasApplied = data.hasApplied || false;
						this.applyCount = data.applyCount || taskInfo.applyCount || 0;
						this.isLiked = taskInfo.liked;
						this.isStarred = taskInfo.starred;
						this.isFollowing = taskInfo.following;
						
						// 如果有报名者列表，则赋值
						if (taskInfo.applicants && taskInfo.applicants.length > 0) {
							this.applicants = taskInfo.applicants;
						}

					} else {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.showToast({
						title: '获取任务详情失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading();
				}
			},
			// 切换收藏状态
			async toggleStar() {
				if (!this.isLogin) {
					return this.showLoginModal();
				}
				this.isStarred = !this.isStarred;
				this.taskInfo.starCount += this.isStarred ? 1 : -1;
				await toggleStar(this.taskId);
			},
			// 关注功能
			async toggleFollow() {
				if (!this.isLogin) {
					return this.showLoginModal();
				}
				if (this.followInProgress) return;
				this.followInProgress = true;

				// 如果是取消关注，则弹窗确认
				if (this.isFollowing) {
					uni.showModal({
						title: '提示',
						content: '确定不再关注该用户吗？',
						success: async (res) => {
							if (res.confirm) {
								await this.performToggleFollow();
							}
							this.followInProgress = false; // 无论如何都解锁
						}
					});
				} else {
					await this.performToggleFollow();
					this.followInProgress = false;
				}
			},
			async performToggleFollow() {
				this.isFollowing = !this.isFollowing;
				try {
					await toggleFollow(this.taskInfo.createBy);
				} catch (e) {
					// 失败了把状态切换回来
					this.isFollowing = !this.isFollowing;
				}
			},
			// 聊一聊功能（待实现）
			chat() {
				uni.showToast({
					title: '聊一聊功能待实现',
					icon: 'none'
				});
			},
			// 显示菜单
			showActionMenu() {
				const itemList = ['分享'];
				if (this.isPublisher) {
					// itemList.push('删除'); // 不再显示删除
				} else {
					itemList.push('举报');
				}

				uni.showActionSheet({
					itemList: itemList,
					success: (res) => {
						const action = itemList[res.tapIndex];
						if (action === '分享') {
							uni.showToast({ title: '分享功能待实现', icon: 'none' });
						} else if (action === '举报') {
							uni.showToast({ title: '举报功能待实现', icon: 'none' });
						}
					}
				});
			},
			// 处理删除
			async handleDelete() {
				// 保留 handleDelete 方法但不再调用
			},
			getImageList(task) {
				if (!task || !task.imageUrls) return [];
				return task.imageUrls.split(',').filter(Boolean).map(url => {
					if (/^https?:\/\//.test(url)) {
						return url;
					} else {
						return config.baseUrl + config.apiPrefix + url;
					}
				});
			},
			maskPhone(phone) {
				if (!phone) return '-';
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			},
			maskEmail(email) {
				if (!email) return '-';
				const idx = email.indexOf('@');
				if (idx <= 2) return email;
				return email.substring(0, 2) + '****' + email.substring(idx);
			},
			maskName(name) {
				if (!name) return '-';
				if (name.length === 2) return name[0] + '*';
				if (name.length > 2) return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
				return name;
			},
			callPhone(phone) {
				if (!phone) return;
				uni.makePhoneCall({ phoneNumber: phone });
			},
			async applyTask() {
				// 添加报名人数已满判断
				if (this.applyCount >= (this.taskInfo.maxApplyCount || 1) && !this.hasApplied) {
					uni.showToast({ title: '报名人数已满', icon: 'none' });
					return;
				}
				// 添加登录检查
				if (!this.isLogin) {
					return this.showLoginModal();
				}
				
				if (!this.hasApplied) {
					try {
						const res = await applyTaskApi(this.taskInfo.taskId);
						if (res.code === 200) {
							this.hasApplied = true;
							this.applyCount = res.data.applyCount || (this.applyCount + 1);
							// 根据返回的消息决定显示什么提示
							if (res.msg === '已报名') {
								// 如果后端返回"已报名"，说明用户之前已经报名了，更新状态但不显示提示
								console.log('用户已报名该任务');
							} else {
								uni.showToast({ title: '报名成功', icon: 'success' });
							}
						} else {
							uni.showToast({ title: res.msg || '报名失败', icon: 'none' });
						}
					} catch (e) {
						uni.showToast({ title: '报名失败', icon: 'none' });
					}
				} else {
					try {
						const res = await cancelApplyTaskApi(this.taskInfo.taskId);
						if (res.code === 200) {
							this.hasApplied = false;
							this.applyCount = res.data.applyCount || (this.applyCount - 1);
							uni.showToast({ title: '已取消报名', icon: 'success' });
						} else {
							uni.showToast({ title: res.msg || '取消报名失败', icon: 'none' });
						}
					} catch (e) {
						uni.showToast({ title: '取消报名失败', icon: 'none' });
					}
				}
			},
			getApplicantAvatar(avatar) {
				if (!avatar) {
					return '/static/default-avatar.png';
				}
				if (avatar.startsWith('http')) {
					return avatar;
				}
				return config.baseUrl + config.apiPrefix + avatar;
			},
			showLoginModal() {
				uni.showModal({
					title: '提示',
					content: '您还未登录，是否前往登录？',
					success: (res) => {
						if (res.confirm) uni.navigateTo({ url: '/pages/login/login' });
					}
				});
			}
		}
	}
</script>

<style lang="scss">
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx; /* 留出底部评论框的高度 */
}

.header-section {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
}

.left-section {
	display: flex;
	align-items: center;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.nickname {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.right-section {
	display: flex;
	align-items: center;
}

.action-menu-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 60rpx;
	height: 60rpx;
	
	.dot {
		font-size: 12px;
		font-weight: bold;
		line-height: 1;
		margin: 0 -2px;
	}
}

.share-icon {
	width: 40rpx;
	height: 40rpx;
}

.task-main-swiper {
	width: 100%;
	height: 320px;
	max-width: 100vw;
	background-color: #f0f0f0;
}

.task-main-image {
	width: 100%;
	height: 100%;
	display: block;
	background-color: #f0f0f0;
	object-fit: contain;
}

.task-content-section {
	padding: 20rpx;
	background-color: #fff;
	margin-bottom: 20rpx;
}

.task-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.task-description {
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
	margin-bottom: 20rpx;
}

.task-meta {
	display: flex;
	justify-content: space-between;
	font-size: 24rpx;
	color: #999;
}

.interaction-counts {
	display: flex;
	justify-content: space-around;
	padding: 20rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
	margin-bottom: 20rpx;
}

.count-item {
	font-size: 28rpx;
	color: #666;
}

.count-number {
	font-size: 20rpx;
	margin-left: 5rpx;
	color: #666;
}

.icon {
	width: 40rpx;
	height: 40rpx;
	vertical-align: middle;
	margin-right: 5rpx;
}

.comment-section {
	padding: 20rpx;
	background-color: #fff;
}

.comment-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.comment-list {
	margin-bottom: 20rpx;
}

.comment-item {
	display: flex;
	flex-direction: column;
	margin-bottom: 20rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.comment-item:last-child {
	border-bottom: none;
}

.comment-user {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.user-avatar {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.user-info {
	display: flex;
	flex-direction: column;
}

.user-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 4rpx;
}

.comment-time {
	font-size: 24rpx;
	color: #999;
}

.comment-content {
	font-size: 28rpx;
	color: #333;
	line-height: 1.5;
	padding-left: 80rpx;
}

.empty-comment {
	text-align: center;
	color: #999;
	font-size: 28rpx;
	padding: 50rpx;
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	display: flex;
	align-items: center;
	padding: 16rpx 30rpx;
	background-color: #fff;
	border-top: 1rpx solid #eee;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
	z-index: 10;
	box-sizing: border-box;
}

.left-actions {
	display: flex;
	align-items: center;
}

.action-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	color: #666;
	font-size: 20rpx;
	margin-right: 40rpx;
}

.action-item .action-icon-img {
	width: 40rpx;
	height: 40rpx;
	margin-bottom: 8rpx;
}

.action-item .text {
	font-size: 22rpx;
	color: #666;
}

.apply-btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	background: linear-gradient(90deg, #ff8800, #ff6600);
	color: #fff;
	font-weight: bold;
	border: none;
	border-radius: 40rpx;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box;
	padding: 0 20rpx;
	cursor: pointer;
}

.apply-btn.applied {
	background: #ccc;
	color: #fff;
}

.apply-btn.disabled {
	background: #ccc !important;
	color: #fff !important;
	pointer-events: none;
}

.loading-tip {
	text-align: center;
	padding: 50rpx;
	color: #999;
	font-size: 28rpx;
}

.applicants-section {
	padding: 20rpx;
	background-color: #ffffff;
	margin-top: 20rpx;

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.applicants-list {
		display: flex;
		flex-wrap: wrap;
	}

	.applicant-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 30rpx;
		margin-bottom: 20rpx;
		width: 120rpx; // 固定宽度
	}

	.applicant-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-bottom: 10rpx;
	}

	.applicant-nickname {
		font-size: 24rpx;
		color: #666;
		text-align: center;
		//-超出省略
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
	}
}

.comment-input-bar {
	display: flex;
	align-items: center;
	padding: 16rpx 20rpx;
	background: #fff;
	border-top: 1rpx solid #eee;
	position: fixed;
	bottom: 100rpx; /* 留出底部操作栏空间 */
	left: 0;
	width: 100%;
	z-index: 11;
}
.comment-input {
	flex: 1;
	height: 64rpx;
	border: 1rpx solid #eee;
	border-radius: 32rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	background: #f7f7f7;
	margin-right: 16rpx;
}
.comment-send-btn {
	min-width: 100rpx;
	height: 64rpx;
	background: linear-gradient(90deg, #ff8800, #ff6600);
	color: #fff;
	border: none;
	border-radius: 32rpx;
	font-size: 28rpx;
	font-weight: bold;
}

.follow-btn {
	padding: 10rpx 32rpx;
	border: 2rpx solid #ff8800;
	border-radius: 30rpx;
	font-size: 26rpx;
	margin-right: 20rpx;
	background: #fff;
	color: #ff8800;
	transition: all 0.2s;
	box-shadow: 0 2rpx 8rpx rgba(255,136,0,0.08);

	&.followed {
		background: linear-gradient(90deg, #ff8800, #ff6600);
		color: #fff;
		border: 2rpx solid #ff8800;
		box-shadow: 0 2rpx 8rpx rgba(255,136,0,0.08);
	}
}

.star-action {
	display: flex;
	flex-direction: row;
	align-items: center;
	padding: 10rpx;
}

.star-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 6rpx;
}

.star-count {
	font-size: 20rpx;
	color: #666;
}
</style> 